package ua.amsoft.brelok.service;

import ua.amsoft.brelok.R;
import ua.amsoft.brelok.manager.WidgetUpdateManager;
import ua.amsoft.brelok.widget.BrelokWidgetProvider;
import android.app.IntentService;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

/**
 * Update service for Brelok application.
 * 
 * @author Tair Mustafaiev
 */
public class UpdateService extends IntentService {
    
    public UpdateService() {
        super("Brelok Update Service");
    }
    
    private static final String TAG = UpdateService.class.getName();
    
    @Override
    public void onCreate() {
        super.onCreate();
    }
    
    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    
    @Override
    protected void onHandleIntent(final Intent intent) {
        Log.i(UpdateService.TAG, "onHandleIntent() started");
        final UpdateTaskProcessor processor = new UpdateTaskProcessor(getApplicationContext());
        processor.update();
        final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
        final ComponentName thisWidget = new ComponentName(this, BrelokWidgetProvider.class);
        final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        
        final RemoteViews updatedViews = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.widget_layout);
        updatedViews.setViewVisibility(R.id.refresh, View.INVISIBLE);
        updatedViews.setViewVisibility(R.id.widget_refresh_progress, View.VISIBLE);
        
        for (final int appWidgetId : appWidgetIds) {
            appWidgetManager.updateAppWidget(appWidgetId, updatedViews);
            WidgetUpdateManager.updateAppWidget(this, appWidgetManager, appWidgetId);
        }
        Log.i(UpdateService.TAG, "onHandleIntent() finished");
    }
    
}
